package com.wangp.enjoywork.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.wangp.enjoywork.entity.SeaMan;
import com.wangp.enjoywork.mapper.SeaManMapper;
import com.wangp.enjoywork.service.FormatService;
import com.wangp.enjoywork.service.GeneratorExcelService;

@Controller
public class ParseController {
	
	@Autowired
	private SeaManMapper seaManMapper;
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private GeneratorExcelService generatorExcelService ;

	@PostMapping("/upload_resume")
	public String receptUploadFiles(HttpServletRequest request, @RequestParam("sign_on") MultipartFile sign_on,
			@RequestParam(value = "sign_off", required = false) MultipartFile sign_off)
			throws IOException, ParseException {
		String ip = request.getRemoteAddr();
		logger.info("收到ip地址为：{}的转化请求", ip);
//		System.out.println("收到转化请求" + ip);

		SeaMan seaMan = new SeaMan();

		// 判断上传文件是否属于excel格式
		if (!FormatService.fileTypeFormatJudgment(sign_on)) {
			request.setAttribute("msg", "上船人员简历格式类型不正确");
			logger.warn("警告：ip地址为{}传入的上船人员简历格式类型不正确", ip);
			return "index";
		}
		if (!sign_off.isEmpty()) {
			if (!FormatService.fileTypeFormatJudgment(sign_off)) {
				request.setAttribute("msg", "下船人员简历格式类型不正确");
				logger.warn("警告：ip地址为{}传入的下船人员简历格式类型不正确", ip);
				return "index";
			}
		}
		
//		System.out.println("判断上传文件是否属于excel格式" + "：完毕！");
		logger.info("ip地址为：{}所上传的文件类型正确，即将开始验证并解析上传文件", ip);
		
		// 解析上船内容是否正确
		if (!FormatService.SignOnContentFormatJudgment(sign_on, seaMan)) {
			request.setAttribute("msg", "上船人员简历为非法格式");
			logger.warn("警告：ip地址为{}传入的上船人员简历为非法格式", ip);
			return "index";
		}

		if (!FormatService.SignOffContentFormatJudgment(sign_off, seaMan)) {
			request.setAttribute("msg", "下船人员简历为非法格式");
			logger.warn("警告：ip地址为{}传入的下船人员简历为非法格式", ip);
			return "index";
		}
		
//		System.out.println("解析上船内容是否正确" + "：完毕！");
		logger.info("ip地址为：{}传入的上下船人员简历解析完毕", ip);

		String baseName = UUID.randomUUID().toString();

		// 生成会签单，保存在服务器
		generatorExcelService.generatorSignSummury(request, seaMan, baseName);
//		System.out.println("生成会签单，保存在服务器" + "：完毕！");
		logger.info("ip地址为：{}请求的会签单已保存在服务器！",ip);
		
		//生成资格评定表，并保存在服务器
		generatorExcelService.generatorQualifyWord(request, seaMan, baseName);
//		System.out.println("生成资格评定表，并保存在服务器" + "：完毕！");
		logger.info("ip地址为：{}请求的资格评定表已保存在服务器！",ip);
		
		logger.info("换人详情："+seaMan.toString()+"----->完毕！");
		
		//保存将此次记录保存至数据库
		seaManMapper.saveSeaMan(seaMan);
		
		//保存上船人员简历
		generatorExcelService.saveSignOnCrewResume(request, sign_on, baseName);
//		System.out.println("生成上船人员简历，并保存在服务器" + "：完毕！");
		logger.info("ip地址为：{}请求的上船人员简历表已保存在服务器！",ip);

		return "success";
	}

	@GetMapping("/download/{fileName}")
	public void outputExcel(HttpServletResponse response, HttpServletRequest request,@PathVariable("fileName") String fileName) throws IOException {

//		HSSFWorkbook workbook = (HSSFWorkbook) request.getAttribute("data");
//
//		response.setContentType("application/octet-stream");
//		response.setHeader("Content-disposition", "attachment;filename=" + "crews.xls");
//		response.flushBuffer();
//		workbook.write(response.getOutputStream());
		
		
		String path = request.getSession().getServletContext().getRealPath(fileName);
		
		System.out.println(path);
		
		File file = new File(path);
		
		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		
		if(file.exists()){
			byte[] flush = new byte[1024];
			FileInputStream fis = new FileInputStream(file);
			ServletOutputStream sos = response.getOutputStream();
			while(fis.read(flush) != -1){
				sos.write(flush);
			}
			sos.flush();
			fis.close();
			sos.close();
		}
//		file.delete();
		
	}

}
